## Function to plot AMCEs results

plot_AMCEs <- function(title, data,
                       facet = FALSE,
                       # xlimit = NULL, 
                       # xbreaks = NULL, 
                       width = 8, height = 12, scale = 1, base_size = 12
                       ) {
  
  df <- data
  
  var_names <- df %>% select(order, var.names) %>% group_by(order, var.names) %>% distinct() %>% ungroup() %>% select(-order)
  var_names <- pull(var_names, var.names)
  
  order <- df %>% select(order) %>% distinct()
  order <- pull(order, order)

  g <- ggplot(df) +
    geom_hline(yintercept = 0, 
               size = .5, 
               colour = "darkgrey", 
               linetype = "solid") +
    geom_point(aes(x = order, 
                   y = Estimate,
                   color = Attribute), 
               na.rm = TRUE) +
    geom_pointrange(aes(x = order,
                        y = Estimate,
                        ymin = lower,
                        ymax = upper, 
                        color = Attribute), 
                    size = 0.75, 
                    fatten = 1.5,
                    na.rm = TRUE) +
    geom_point(data = filter(df, is.na(Estimate)  & !is.na(Level)),
               aes(x = order, 
                   y = 0,
                   color = Attribute),
               size = 1.75,
               na.rm = TRUE) +
    coord_flip(ylim = c(-0.5, 0.5)) +
    scale_y_continuous(breaks = seq(-0.4, 0.4, 0.2),
                       labels = c("-40%", "-20%", "0%", "20%", "40%")) +
    # coord_flip() +
    ylab("Average Marginal Component Effect") +
    set_my_ggtheme(base_size = base_size) +  # mytheme(11) for PowerPoint
    scale_x_continuous(name = NULL,
                       breaks = order,
#                       breaks = 1:nrow(df),
                       labels = var_names) +
#                       labels = df$var.names)
    ggtitle(title)
  
  # if (is.null(xlimit) & is.null(xbreaks)){
  #   g <- g + 
  #     ylab("Average Marginal Component Effect")
  # } else if (!is.null(xlimit) & !is.null(xbreaks)) {
  #   g <- g + 
  #     scale_y_continuous(name = "Average Marginal Component Effect",
  #                        breaks = xbreaks,
  #                        limit = xlimit) 
  # } else{
  #   stop("xlimit and xbreaks: set both or do not set")
  # }

  # if (facet == TRUE){
  #   g <- g +
  #     ggtitle(title) +
  #     facet_wrap(~ facetvar, nrow = 1)
  # } else {
  #   g <- g +
  #     ggtitle(paste0(title, " (N = ", df[1, "nobs"], ")"))
  # }

  ggsave(paste0("figures/", title, ".pdf"), 
         plot = g, width = width, height = height, scale = scale)
  
  return(g)
  
}
